import { get, post, put, del } from '@/utils/request'

// 获取保证金统计
export function getDepositStats() {
  return get('/deposit/stats')
}

// 获取保证金记录
export function getDepositRecords(params = {}) {
  return get('/deposit/records', params)
}

// 获取保证金记录详情
export function getDepositRecordDetail(recordId) {
  return get(`/deposit/records/${recordId}`)
}

// 充值保证金
export function payDeposit(data) {
  return post('/deposit/pay', data, {
    showLoading: true,
    loadingText: '充值保证金中...'
  })
}

// 申请保证金退还
export function applyDepositRefund(data) {
  return post('/deposit/refund/apply', data, {
    showLoading: true,
    loadingText: '申请退还中...'
  })
}

// 获取保证金退还申请列表
export function getRefundApplications(params = {}) {
  return get('/deposit/refund/applications', params)
}

// 取消保证金退还申请
export function cancelRefundApplication(applicationId) {
  return post(`/deposit/refund/applications/${applicationId}/cancel`)
}

// 获取服务类型保证金要求
export function getServiceDepositRequirements() {
  return get('/deposit/service-requirements')
}

// 获取已缴纳保证金的服务类型
export function getPaidServiceTypes() {
  return get('/deposit/paid-service-types')
}

// 获取扣款优先级设置
export function getDeductionPriority() {
  return get('/deposit/deduction-priority')
}

// 更新扣款优先级设置
export function updateDeductionPriority(priority) {
  return put('/deposit/deduction-priority', { priority })
}

// 获取保证金冻结记录
export function getFreezeRecords(params = {}) {
  return get('/deposit/freeze-records', params)
}

// 获取保证金扣除记录
export function getDeductionRecords(params = {}) {
  return get('/deposit/deduction-records', params)
}

// 申请保证金解冻
export function applyUnfreeze(freezeId, reason) {
  return post(`/deposit/unfreeze/apply/${freezeId}`, { reason })
}

// 获取保证金余额详情
export function getDepositBalance(serviceType = null) {
  const params = serviceType ? { serviceType } : {}
  return get('/deposit/balance', params)
}

// 导出保证金记录
export function exportDepositRecords(params = {}) {
  return get('/deposit/records/export', params, {
    responseType: 'blob'
  })
}

// 获取保证金使用分析
export function getDepositAnalysis(timeRange = '30d') {
  return get('/deposit/analysis', { timeRange })
}

// 获取风险评估
export function getRiskAssessment() {
  return get('/deposit/risk-assessment')
}

// 获取保证金配置
export function getDepositConfig() {
  return get('/deposit/config')
}

// 更新保证金配置
export function updateDepositConfig(config) {
  return put('/deposit/config', config)
}

// 检查保证金状态
export function checkDepositStatus(serviceType) {
  return get(`/deposit/status/${serviceType}`)
}

// 批量充值保证金
export function batchPayDeposit(data) {
  return post('/deposit/batch-pay', data, {
    showLoading: true,
    loadingText: '批量充值中...'
  })
}

// 获取保证金变动历史
export function getDepositHistory(params = {}) {
  return get('/deposit/history', params)
}

// 保证金记录类型常量
export const DEPOSIT_RECORD_TYPES = {
  DEPOSIT: 'deposit',         // 充值
  FREEZE: 'freeze',           // 冻结
  UNFREEZE: 'unfreeze',       // 解冻
  DEDUCT: 'deduct',           // 扣除
  REFUND: 'refund',           // 退还
  TRANSFER: 'transfer'        // 转移
}

export const DEPOSIT_RECORD_TYPE_TEXT = {
  [DEPOSIT_RECORD_TYPES.DEPOSIT]: '充值',
  [DEPOSIT_RECORD_TYPES.FREEZE]: '冻结',
  [DEPOSIT_RECORD_TYPES.UNFREEZE]: '解冻',
  [DEPOSIT_RECORD_TYPES.DEDUCT]: '扣除',
  [DEPOSIT_RECORD_TYPES.REFUND]: '退还',
  [DEPOSIT_RECORD_TYPES.TRANSFER]: '转移'
}

export const DEPOSIT_RECORD_TYPE_COLOR = {
  [DEPOSIT_RECORD_TYPES.DEPOSIT]: 'success',
  [DEPOSIT_RECORD_TYPES.FREEZE]: 'danger',
  [DEPOSIT_RECORD_TYPES.UNFREEZE]: 'success',
  [DEPOSIT_RECORD_TYPES.DEDUCT]: 'danger',
  [DEPOSIT_RECORD_TYPES.REFUND]: 'primary',
  [DEPOSIT_RECORD_TYPES.TRANSFER]: 'info'
}

// 保证金状态常量
export const DEPOSIT_STATUS = {
  PENDING: 'pending',         // 待处理
  PROCESSING: 'processing',   // 处理中
  COMPLETED: 'completed',     // 已完成
  FAILED: 'failed',           // 失败
  CANCELLED: 'cancelled'      // 已取消
}

export const DEPOSIT_STATUS_TEXT = {
  [DEPOSIT_STATUS.PENDING]: '待处理',
  [DEPOSIT_STATUS.PROCESSING]: '处理中',
  [DEPOSIT_STATUS.COMPLETED]: '已完成',
  [DEPOSIT_STATUS.FAILED]: '失败',
  [DEPOSIT_STATUS.CANCELLED]: '已取消'
}

export const DEPOSIT_STATUS_COLOR = {
  [DEPOSIT_STATUS.PENDING]: 'warning',
  [DEPOSIT_STATUS.PROCESSING]: 'primary',
  [DEPOSIT_STATUS.COMPLETED]: 'success',
  [DEPOSIT_STATUS.FAILED]: 'danger',
  [DEPOSIT_STATUS.CANCELLED]: 'info'
}

// 扣款优先级常量
export const DEDUCTION_PRIORITY = {
  BALANCE_FIRST: 'balance_first',   // 优先扣除余额
  DEPOSIT_FIRST: 'deposit_first'    // 优先扣除保证金
}

export const DEDUCTION_PRIORITY_TEXT = {
  [DEDUCTION_PRIORITY.BALANCE_FIRST]: '优先扣除可提现余额',
  [DEDUCTION_PRIORITY.DEPOSIT_FIRST]: '优先扣除保证金'
}

// 服务类型保证金配置
export const SERVICE_DEPOSIT_CONFIG = {
  LAUNDRY: { type: 'laundry', name: '衣物洗护', deposit: 500, description: '提供各类衣物清洗、熨烫、保养服务' },
  SHOES: { type: 'shoes', name: '鞋类清洗', deposit: 300, description: '专业鞋类清洗、护理、修复服务' },
  PETS: { type: 'pet', name: '宠物用品', deposit: 1000, description: '宠物服装、用品清洗消毒服务' },
  BAGS: { type: 'bag', name: '包包护理', deposit: 400, description: '各类包包清洗、保养、修复服务' },
  BEDDING: { type: 'bedding', name: '床上用品', deposit: 600, description: '床单、被套、枕头等床上用品清洗' },
  CAR: { type: 'car', name: '汽车清洗', deposit: 3000, description: '汽车内外清洗、美容、保养服务' },
  HOME_CLEANING: { type: 'home_cleaning', name: '家政清洁', deposit: 2000, description: '家庭深度清洁、保洁服务' },
  PLUMBING: { type: 'plumbing', name: '管道疏通', deposit: 500, description: '管道疏通、维修、清洁服务' }
}

// 获取记录类型颜色
export function getRecordTypeColor(type) {
  return DEPOSIT_RECORD_TYPE_COLOR[type] || 'info'
}

// 获取记录类型文本
export function getRecordTypeText(type) {
  return DEPOSIT_RECORD_TYPE_TEXT[type] || type
}

// 获取状态颜色
export function getStatusColor(status) {
  return DEPOSIT_STATUS_COLOR[status] || 'info'
}

// 获取状态文本
export function getStatusText(status) {
  return DEPOSIT_STATUS_TEXT[status] || status
}

// 获取金额前缀
export function getAmountPrefix(type) {
  const prefixMap = {
    [DEPOSIT_RECORD_TYPES.DEPOSIT]: '+',
    [DEPOSIT_RECORD_TYPES.FREEZE]: '',
    [DEPOSIT_RECORD_TYPES.UNFREEZE]: '+',
    [DEPOSIT_RECORD_TYPES.DEDUCT]: '-',
    [DEPOSIT_RECORD_TYPES.REFUND]: '+',
    [DEPOSIT_RECORD_TYPES.TRANSFER]: ''
  }
  return prefixMap[type] || ''
}

// 获取金额样式类
export function getAmountClass(type) {
  const classMap = {
    [DEPOSIT_RECORD_TYPES.DEPOSIT]: 'amount-positive',
    [DEPOSIT_RECORD_TYPES.FREEZE]: 'amount-neutral',
    [DEPOSIT_RECORD_TYPES.UNFREEZE]: 'amount-positive',
    [DEPOSIT_RECORD_TYPES.DEDUCT]: 'amount-negative',
    [DEPOSIT_RECORD_TYPES.REFUND]: 'amount-positive',
    [DEPOSIT_RECORD_TYPES.TRANSFER]: 'amount-neutral'
  }
  return classMap[type] || ''
}

// 获取服务类型名称
export function getServiceTypeName(type) {
  const config = Object.values(SERVICE_DEPOSIT_CONFIG).find(item => item.type === type)
  return config ? config.name : type
}

// 获取服务类型保证金金额
export function getServiceDepositAmount(type) {
  const config = Object.values(SERVICE_DEPOSIT_CONFIG).find(item => item.type === type)
  return config ? config.deposit : 0
}

// 安全检查支付状态
export function checkDepositPaymentStatus(orderId) {
  return get(`/deposit/pay/status/${orderId}`, {}, {
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'X-CSRF-Token': getCsrfToken()
    }
  })
}

// 获取CSRF Token
function getCsrfToken() {
  // 从meta标签或cookie中获取CSRF token
  const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ||
                document.cookie.split('; ').find(row => row.startsWith('csrf_token='))?.split('=')[1]
  return token || ''
}